package com.agger.harmonyosthemeseditor.abilities.slices;

import com.agger.harmonyosthemeseditor.ResourceTable;
import com.agger.harmonyosthemeseditor.ThemesEditorAbility;
import com.agger.harmonyosthemeseditor.intelligent.DatabaseManager;
import com.agger.harmonyosthemeseditor.intelligent.GeneralUtil;
import com.agger.harmonyosthemeseditor.userinterface.ResourceTool;
import com.huawei.agconnect.remoteconfig.AGConnectConfig;
import com.huawei.agconnect.remoteconfig.ConfigValues;
import com.huawei.hms.analytics.HiAnalyticsTools;
import ohos.aafwk.ability.AbilitySlice;
import ohos.aafwk.ability.AbilitySliceAnimator;
import ohos.aafwk.content.Intent;
import ohos.agp.colors.RgbColor;
import ohos.agp.components.Component;
import ohos.agp.components.ScrollView;
import ohos.agp.components.StackLayout;
import ohos.agp.components.Text;
import ohos.agp.text.RichText;
import ohos.agp.text.RichTextBuilder;
import ohos.agp.text.TextForm;
import ohos.agp.utils.LayoutAlignment;
import ohos.agp.window.service.DisplayAttributes;
import ohos.agp.window.service.DisplayManager;
import ohos.agp.window.service.WindowManager;
import ohos.global.configuration.DeviceCapability;

public class GuideSlice extends AbilitySlice
{
    private int RichTextCode = -1;

    @Override
    public void onStart(Intent intent)
    {
        super.onStart(intent);
        super.setUIContent(ResourceTable.Layout_slice_guide);
        //设定状态栏沉浸
        getWindow().setStatusBarColor(ResourceTool.getColor(this,ResourceTable.Color_dawnlighti_statusbar_guide,0xF8EDD9));
        getWindow().setNavigationBarColor(ResourceTool.getColor(this,ResourceTable.Color_dawnlighti_navigationbar_guide,0xF8EDD9));
        int CurrentColorMode = getColorMode();
        if(CurrentColorMode == 0) this.getWindow().setStatusBarVisibility(0);
        else if(CurrentColorMode == 1) this.getWindow().setStatusBarVisibility(2052);
        this.getWindow().setBackgroundColor(RgbColor.fromArgbInt(ResourceTool.getColor(this,ResourceTable.Color_dawnlighti_statusbar_guide,0xF8EDD9)));
        GeneralUtil.setWindowToMaxRefreshRate(getWindow());
        DisplayAttributes displayAttributes = DisplayManager.getInstance().getDefaultDisplay(getContext()).get().getAttributes();
        if(displayAttributes.width>displayAttributes.height)
        {
            getWindow().addFlags(WindowManager.LayoutConfig.MARK_TRANSLUCENT_STATUS|WindowManager.LayoutConfig.MARK_TRANSLUCENT_NAVIGATION|WindowManager.LayoutConfig.MARK_FULL_SCREEN);
        }
        ThemesEditorAbility.isGuideSlice = true;
        ThemesEditorAbility.Instance.GuideSlice = this;
        try
        {
            AbilitySliceAnimator abilitySliceAnimator = new AbilitySliceAnimator(DisplayManager.getInstance().getDefaultDisplay(getContext()).get().getAttributes().width*GeneralUtil.SliceAnimatorDepth,0,0,0);
            abilitySliceAnimator.setDuration(GeneralUtil.SliceAnimatorDuration);
            getAbility().setAbilitySliceAnimator(abilitySliceAnimator);
        }catch (Exception ex){ex.printStackTrace();}
        findComponentById(ResourceTable.Id_GuideSlice_CancelButton).setClickedListener(c->{Quit();});
        findComponentById(ResourceTable.Id_GuideSlice_AgreeButton).setClickedListener(c->{Launch();});
        ScrollView BottomScroller = (ScrollView) findComponentById(ResourceTable.Id_Guide_BottomScroller);
        Component BottomContent = findComponentById(ResourceTable.Id_Guide_Bottom_Content);
        if(ThemesEditorAbility.API_Version_Code>=7) BottomScroller.setEnabled(true);
        Text text = (Text)findComponentById(ResourceTable.Id_GuideSlice_BotomRichText);
        String BottomText = "本服务需$联网$，获取应用信息、网络信息、设备信息、个性化信息，以及您主动上传的数据，用于为您提供主题协作相关服务。点击“同意”，即表示您同意上述内容及$主题协作器用户协议$、$关于主题协作器与隐私权的声明$。";
        try{BottomText = getResourceManager().getElement(ResourceTable.String_GuideScene_BottomText).getString();}catch (Exception ex){}
        String[] BottomTexts = BottomText.split("\\$");
        int textSize = (int)((10f*displayAttributes.scalDensity)+0.5f);
        int textColor = ResourceTool.getColor(getContext(),ResourceTable.Color_dawnlighti_text_secondary,0);
        int textColor_hint = ResourceTool.getColor(getContext(),ResourceTable.Color_dawnlighti_text_primary,0);
        int textColor_accent = ResourceTool.getColor(getContext(),ResourceTable.Color_dawnlighti_accent,0);

        RichTextBuilder builder = new RichTextBuilder();
        builder.mergeForm(new TextForm().setTextSize(textSize).setTextColor(textColor));
        builder.addText(BottomTexts[0]);
        builder.revertForm();
        builder.mergeForm(new TextForm().setTextSize(textSize).setTextColor(textColor_hint));
        builder.addText(BottomTexts[1]);
        builder.revertForm();
        builder.mergeForm(new TextForm().setTextSize(textSize).setTextColor(textColor));
        builder.addText(BottomTexts[2]);
        builder.revertForm();
        builder.mergeForm(new TextForm().setTextSize(textSize).setTextColor(textColor_accent));
        builder.addText(BottomTexts[3]);
        builder.revertForm();
        builder.mergeForm(new TextForm().setTextSize(textSize).setTextColor(textColor));
        builder.addText(BottomTexts[4]);
        builder.revertForm();
        builder.mergeForm(new TextForm().setTextSize(textSize).setTextColor(textColor_accent));
        builder.addText(BottomTexts[5]);
        builder.revertForm();
        builder.mergeForm(new TextForm().setTextSize(textSize).setTextColor(textColor));
        builder.addText(BottomTexts[6]);
        RichText richTextContent = builder.build();
        text.setRichText(richTextContent);
        RichTextCode = -1;
        richTextContent.addTouchEventListener((component, touchEvent) ->
        {
            if(touchEvent.getAction() == 1) RichTextCode = 0;
            return true;
        },BottomTexts[0].length()+BottomTexts[1].length()+BottomTexts[2].length(),BottomTexts[0].length()+BottomTexts[1].length()+BottomTexts[2].length()+BottomTexts[3].length()-1);
        richTextContent.addTouchEventListener((component, touchEvent) ->
        {
            if(touchEvent.getAction() == 1) RichTextCode = 1;
            return true;
        },BottomTexts[0].length()+BottomTexts[1].length()+BottomTexts[2].length()+BottomTexts[3].length()+BottomTexts[4].length(),BottomTexts[0].length()+BottomTexts[1].length()+BottomTexts[2].length()+BottomTexts[3].length()+BottomTexts[4].length()+BottomTexts[5].length()-1);
        text.setClickedListener(c->
        {
            if(RichTextCode == 0)
            {
                RichTextCode = -1;
                onClickNewScene("UserAgreement");
            }else if(RichTextCode == 1)
            {
                RichTextCode = -1;
                onClickNewScene("PrivacyStatement");
            }
        });
        /*if(ThemesEditorAbility.API_Version_Code<7)
        {
            RichTextBuilder builder = new RichTextBuilder();
            builder.mergeForm(new TextForm().setTextSize(textSize).setTextColor(textColor));
            builder.addText(BottomTexts[0]);
            builder.revertForm();
            builder.mergeForm(new TextForm().setTextSize(textSize).setTextColor(textColor_hint));
            builder.addText(BottomTexts[1]);
            builder.revertForm();
            builder.mergeForm(new TextForm().setTextSize(textSize).setTextColor(textColor));
            builder.addText(BottomTexts[2]);
            builder.revertForm();
            builder.mergeForm(new TextForm().setTextSize(textSize).setTextColor(textColor_accent));
            builder.addText(BottomTexts[3]);
            builder.revertForm();
            builder.mergeForm(new TextForm().setTextSize(textSize).setTextColor(textColor));
            builder.addText(BottomTexts[4]);
            builder.revertForm();
            builder.mergeForm(new TextForm().setTextSize(textSize).setTextColor(textColor_accent));
            builder.addText(BottomTexts[5]);
            builder.revertForm();
            builder.mergeForm(new TextForm().setTextSize(textSize).setTextColor(textColor));
            builder.addText(BottomTexts[6]);
            RichText richTextContent = builder.build();
            text.setRichText(richTextContent);
            RichTextCode = -1;
            richTextContent.addTouchEventListener((component, touchEvent) ->
            {
                if(touchEvent.getAction() == 1) RichTextCode = 0;
                return true;
            },BottomTexts[0].length()+BottomTexts[1].length()+BottomTexts[2].length(),BottomTexts[0].length()+BottomTexts[1].length()+BottomTexts[2].length()+BottomTexts[3].length()-1);
            richTextContent.addTouchEventListener((component, touchEvent) ->
            {
                if(touchEvent.getAction() == 1) RichTextCode = 1;
                return true;
            },BottomTexts[0].length()+BottomTexts[1].length()+BottomTexts[2].length()+BottomTexts[3].length()+BottomTexts[4].length(),BottomTexts[0].length()+BottomTexts[1].length()+BottomTexts[2].length()+BottomTexts[3].length()+BottomTexts[4].length()+BottomTexts[5].length()-1);
            text.setClickedListener(c->
            {
                if(RichTextCode == 0)
                {
                    RichTextCode = -1;
                    onClickNewScene("UserAgreement");
                }else if(RichTextCode == 1)
                {
                    RichTextCode = -1;
                    onClickNewScene("PrivacyStatement");
                }
            });
        }else
        {
            RichText richTextContent = new RichText(BottomText.replaceAll("\\$",""));
            richTextContent.setRichStyle(new RangedRichStyle(BottomTexts[0].length()+BottomTexts[1].length()+BottomTexts[2].length(),BottomTexts[0].length()+BottomTexts[1].length()+BottomTexts[2].length()+BottomTexts[3].length(), RangedRichStyle.Flag.INCLUDE_START_AND_END,new ClickRichStyle(component-> onClickNewScene("UserAgreement"))));
            richTextContent.setRichStyle(new RangedRichStyle(BottomTexts[0].length()+BottomTexts[1].length()+BottomTexts[2].length()+BottomTexts[3].length()+BottomTexts[4].length(),BottomTexts[0].length()+BottomTexts[1].length()+BottomTexts[2].length()+BottomTexts[3].length()+BottomTexts[4].length()+BottomTexts[5].length(), RangedRichStyle.Flag.INCLUDE_START_AND_END,new ClickRichStyle(component-> onClickNewScene("PrivacyStatement"))));
            richTextContent.setRichStyle(new FontSizeRichStyle(textSize, Text.TextSizeType.PX),0,BottomTexts[0].length(), RangedRichStyle.Flag.INCLUDE_START_AND_END);
            richTextContent.setRichStyle(new FontSizeRichStyle(textSize, Text.TextSizeType.PX),BottomTexts[0].length(),BottomTexts[0].length()+BottomTexts[1].length(), RangedRichStyle.Flag.INCLUDE_START_AND_END);
            richTextContent.setRichStyle(new FontSizeRichStyle(textSize, Text.TextSizeType.PX),BottomTexts[0].length()+BottomTexts[1].length(),BottomTexts[0].length()+BottomTexts[1].length()+BottomTexts[2].length(), RangedRichStyle.Flag.INCLUDE_START_AND_END);
            richTextContent.setRichStyle(new FontSizeRichStyle(textSize, Text.TextSizeType.PX),BottomTexts[0].length()+BottomTexts[1].length()+BottomTexts[2].length(),BottomTexts[0].length()+BottomTexts[1].length()+BottomTexts[2].length()+BottomTexts[3].length(), RangedRichStyle.Flag.INCLUDE_START_AND_END);
            richTextContent.setRichStyle(new FontSizeRichStyle(textSize, Text.TextSizeType.PX),BottomTexts[0].length()+BottomTexts[1].length()+BottomTexts[2].length()+BottomTexts[3].length(),BottomTexts[0].length()+BottomTexts[1].length()+BottomTexts[2].length()+BottomTexts[3].length()+BottomTexts[4].length(), RangedRichStyle.Flag.INCLUDE_START_AND_END);
            richTextContent.setRichStyle(new FontSizeRichStyle(textSize, Text.TextSizeType.PX),BottomTexts[0].length()+BottomTexts[1].length()+BottomTexts[2].length()+BottomTexts[3].length()+BottomTexts[4].length(),BottomTexts[0].length()+BottomTexts[1].length()+BottomTexts[2].length()+BottomTexts[3].length()+BottomTexts[4].length()+BottomTexts[5].length(), RangedRichStyle.Flag.INCLUDE_START_AND_END);
            richTextContent.setRichStyle(new FontSizeRichStyle(textSize, Text.TextSizeType.PX),BottomTexts[0].length()+BottomTexts[1].length()+BottomTexts[2].length()+BottomTexts[3].length()+BottomTexts[4].length()+BottomTexts[5].length(),BottomTexts[0].length()+BottomTexts[1].length()+BottomTexts[2].length()+BottomTexts[3].length()+BottomTexts[4].length()+BottomTexts[5].length()+BottomTexts[6].length(), RangedRichStyle.Flag.INCLUDE_START_AND_END);
            richTextContent.setRichStyle(new ForegroundColorRichStyle(new Color(textColor)),0,BottomTexts[0].length(), RangedRichStyle.Flag.INCLUDE_START_AND_END);
            richTextContent.setRichStyle(new ForegroundColorRichStyle(new Color(textColor_hint)),BottomTexts[0].length(),BottomTexts[0].length()+BottomTexts[1].length(), RangedRichStyle.Flag.INCLUDE_START_AND_END);
            richTextContent.setRichStyle(new ForegroundColorRichStyle(new Color(textColor)),BottomTexts[0].length()+BottomTexts[1].length(),BottomTexts[0].length()+BottomTexts[1].length()+BottomTexts[2].length(), RangedRichStyle.Flag.INCLUDE_START_AND_END);
            richTextContent.setRichStyle(new ForegroundColorRichStyle(new Color(textColor_accent)),BottomTexts[0].length()+BottomTexts[1].length()+BottomTexts[2].length(),BottomTexts[0].length()+BottomTexts[1].length()+BottomTexts[2].length()+BottomTexts[3].length(), RangedRichStyle.Flag.INCLUDE_START_AND_END);
            richTextContent.setRichStyle(new ForegroundColorRichStyle(new Color(textColor)),BottomTexts[0].length()+BottomTexts[1].length()+BottomTexts[2].length()+BottomTexts[3].length(),BottomTexts[0].length()+BottomTexts[1].length()+BottomTexts[2].length()+BottomTexts[3].length()+BottomTexts[4].length(), RangedRichStyle.Flag.INCLUDE_START_AND_END);
            richTextContent.setRichStyle(new ForegroundColorRichStyle(new Color(textColor_accent)),BottomTexts[0].length()+BottomTexts[1].length()+BottomTexts[2].length()+BottomTexts[3].length()+BottomTexts[4].length(),BottomTexts[0].length()+BottomTexts[1].length()+BottomTexts[2].length()+BottomTexts[3].length()+BottomTexts[4].length()+BottomTexts[5].length(), RangedRichStyle.Flag.INCLUDE_START_AND_END);
            richTextContent.setRichStyle(new ForegroundColorRichStyle(new Color(textColor)),BottomTexts[0].length()+BottomTexts[1].length()+BottomTexts[2].length()+BottomTexts[3].length()+BottomTexts[4].length()+BottomTexts[5].length(),BottomTexts[0].length()+BottomTexts[1].length()+BottomTexts[2].length()+BottomTexts[3].length()+BottomTexts[4].length()+BottomTexts[5].length()+BottomTexts[6].length(), RangedRichStyle.Flag.INCLUDE_START_AND_END);
            text.setRichText(richTextContent);
        }*/
        int deviceType = getResourceManager().getDeviceCapability().deviceType;
        if(deviceType != DeviceCapability.DEVICE_TYPE_TV)
        {
            findComponentById(ResourceTable.Id_Guide_Root_Container).setLayoutRefreshedListener(c->
            {
                if(BottomContent.getHeight()>BottomScroller.getHeight())
                {
                    StackLayout.LayoutConfig layoutConfig = (StackLayout.LayoutConfig)BottomContent.getLayoutConfig();
                    layoutConfig.alignment = LayoutAlignment.TOP|LayoutAlignment.HORIZONTAL_CENTER;
                    BottomContent.setLayoutConfig(layoutConfig);
                    BottomScroller.setEnabled(true);
                }
            });
        }
        System.gc();
    }

    private void onClickNewScene(String SceneName)
    {
        try
        {
            Class<AbilitySlice> c = (Class<AbilitySlice>) Class.forName("com.agger.harmonyosthemeseditor.abilities.slices."+SceneName+"Slice");
            AbilitySlice abilitySlice = c.newInstance();
            present(abilitySlice,getAbility().getIntent());
        }catch (Exception ex){}
    }

    @Override
    public void onBackPressed() {Quit();}

    void Launch()
    {
        DatabaseManager.Init(this);
        DatabaseManager.setString("GuideFinished","Yes");
        // 打开华为分析的日志开关
        try
        {
            HiAnalyticsTools.enableLog();
            /*应用遵循数据最小化原则，暂不需要采集额外信息
            ThemesEditorAbility.hiAnalyticsInstance = HiAnalytics.getInstance(getAbility());
            ThemesEditorAbility.hiAnalyticsInstance.setUserProfile("userKey",ThemesEditorAbility.hiAnalyticsInstance.getAAID());
            //自定义埋点，在工程合适位置插入埋点代码
            PacMap pacMap = new PacMap();
            pacMap.putString("type", "other");
            pacMap.putString("content", "我想反馈一下问题，这只是测试采集SDK是否成功接入~");
            pacMap.putString("time", GeneralUtil.getTimeStr());
            ThemesEditorAbility.hiAnalyticsInstance.onEvent("Feedback_ThemesEditor", pacMap);*/
        }catch (Exception ex) {}
        ThemesEditorAbility.isGuideSlice = false;
        try
        {
            ThemesEditorAbility.Instance.config = AGConnectConfig.getInstance();
            ThemesEditorAbility.Instance.config.applyDefault(ResourceTable.Profile_configdefault);
            int i = 0;
            String ConfigType = "Local";
            while((i<3)||((ConfigType.equals("Local"))&&(i<8)))
            {
                ConfigValues last = ThemesEditorAbility.Instance.config.loadLastFetched();
                ThemesEditorAbility.Instance.config.apply(last);
                ThemesEditorAbility.Instance.config.fetch(3600)
                        .addOnSuccessListener(configValues -> {})
                        .addOnFailureListener(e -> {});
                ConfigType = ThemesEditorAbility.Instance.config.getValueAsString("ConfigType");
                i++;
            }
        }catch (Exception e){}
        if(ThemesEditorAbility.ShareFa_Info!=null&&ThemesEditorAbility.ShareFa_Info.equals("ShareFa_BlindBox"))
        {
            DatabaseManager.setString("LastAbilityName","ThemesBlindBox");
            DatabaseManager.setString("ThemesBlindBox_ModeValue","Unpack");
        }
        try
        {
            AbilitySliceAnimator abilitySliceAnimator = new AbilitySliceAnimator(0,0,0,0);
            abilitySliceAnimator.setDuration(0);
            getAbility().setAbilitySliceAnimator(abilitySliceAnimator);
        }catch (Exception ex){ex.printStackTrace();}
        try
        {
            GeneralUtil.writeRawFileToFile(this,"shortcuts_app_manager",getFilesDir()+"/shortcuts_app_manager.png");
            GeneralUtil.writeRawFileToFile(this,"shortcuts_check_update",getFilesDir()+"/shortcuts_check_update.png");
            GeneralUtil.addDynamicShortcuts(GeneralUtil.getAbilityShellActivity(this),new String[]{"AppManager","CheckUpdate"},new String[]{ResourceTool.getString(this,ResourceTable.String_Shortcuts_info,"应用信息"),ResourceTool.getString(this,ResourceTable.String_Shortcuts_update,"检查更新")},new Object[]{GeneralUtil.getBitmapFromFile(getFilesDir()+"/shortcuts_app_manager.png"),GeneralUtil.getBitmapFromFile(getFilesDir()+"/shortcuts_check_update.png")});
        }catch (Exception ex){ex.printStackTrace();}
        present(new MainSceneSlice(), new Intent());
        this.terminate();
    }

    void Quit()
    {
        ThemesEditorAbility.isGuideSlice = false;
        System.gc();
        terminateAbility();
    }

    @Override
    public void onActive() { super.onActive(); }

    @Override
    public void onForeground(Intent intent) { super.onForeground(intent); }
}